<!-- 这是我的票券页面 -->
<template>
  <div class="c-pb100">
    <div>
      <div v-if="from != 'reservation'" class="c-ph24 c-pv30 c-flex-row c-pb30 c-bg-white" @click="goActivityDetail">
        <div class="c-flex-shrink0 c-ww180 c-hh120 c-br16 c-text-hidden c-p">
          <CoverImg :coverSizeClass="'c-w100 c-h c-br16 c-text-hidden'" imgClass="c-br16" :coverUrl="$addXossFilter(activityInfo.poster, require('@/assets/activity_defult.png'))" />
        </div>
        <div class="c-pl20 c-flex-grow1 c-maxh180 c-flex-column c-justify-sb">
          <div class="c-fs24 c-lh36 c-fc-xblack c-ww-bw c-ww-ba c-text-ellipsis2">{{activityInfo.name}}</div>
          <div class="c-fs20 c-fc-gray">时间：{{enrollStartAt}}至{{enrollEndAt}}</div>
        </div>
      </div>
      <div class="c-pv30 c-bd-t12-f5">
        <div v-if="from == 'share'" class="c-fs26 c-fw600 c-ph24">我的票券：{{total}}</div>
        <div v-else>
          <div class="c-fs28 c-fc-xblack c-pb20 c-ph24" v-if="isSignRepeatedly == 1">{{signName}}</div>
          <div class="c-fs28 c-fc-xblack c-pb20 c-ph24" v-if="signStatus==1">请选择要签到的票券</div>
        </div>
        <div v-if="from != 'reservation' && (signStatus == 1 || asId == 0)" v-for="(item, index) in ticketList" :key="item.ticketNo" @click="clickSelectList(index)" class="c-p c-pz1 c-text-hidden c-mh24 c-mt30" :class="item.status == -1 ? 'c-filter-gray100' : ''">
          <div class="c-br16 c-p c-pz1 c-fs24" :class="item.status == -1 ? 'c-fc-gray c-bd1-f6' : 'c-fc-sblack theme-bd1-50'" @click="toTicketNum(item.status, item.receiveUserId)">
            <div class="c-pa c-p-t0 c-p-l0 c-br-tl16 c-br-tr16 c-pz-1 c-w100 c-hh100 theme-bg-gradient18020 c-opacity40"></div>
            <div class="c-p c-pz10 c-flex-row c-pv26 c-ph24" :class="isShowGift(item) ? 'c-bd-dd1' : ''">
              <i v-if="isShowGift(item)" class="c-ww20 c-hh20 c-bg-white c-brp50 c-pa c-pz10 c-p-lm10 c-p-bm10" :class="item.status == -1 ? 'c-bd1-f6' : 'theme-bd1-50'"></i>
              <i v-if="isShowGift(item)" class="c-ww20 c-hh20 c-bg-white c-brp50 c-pa c-pz10 c-p-rm10 c-p-bm10" :class="item.status == -1 ? 'c-bd1-f6' : 'theme-bd1-50'"></i>
              <i v-if="item.status == 0" class="iconfont c-pa c-p-rm12 c-p-t0 theme-fc c-fs80">&#xe874;</i>
              <div v-else :class="getStatusClass(item)" class="c-fc-white c-hh32 c-ph12 c-br-tr16 c-br-bl12 c-fs20 c-pa c-p-r-2 c-p-t0 c-flex-row c-aligni-center">
                {{item.receiveUserId != 0 && item.receiveUserId != userId ? '已领取' : statusMap[item.status]}}
              </div>
              <!-- 勾选框 -->
              <div v-show="showShare || from == 'signin'" class="c-flex-shrink0 c-mr20 c-pt4">
                <span v-show="item.isChecked == 1 && !isReceiveGift(item)" class="iconfont c-fs28 theme-fc">&#xe796;</span>
                <span v-if="showShare" v-show="item.isChecked != 1 && item.receiveUserId == 0 && item.status == 1 && !isReceiveGift(item)" class="iconfont c-fs28 c-fc-gray">&#xe6f7;</span>
                <span v-else-if="from == 'signin'" v-show="item.isChecked != 1 && item.status == 1" class="iconfont c-fs28 c-fc-gray">&#xe6f7;</span>
                <div v-show="item.status != 1 || (item.receiveUserId != 0 && from != 'signin' && from != 'reservation') || isReceiveGift(item)" class="c-ww26 c-hh26 c-brp50 c-bg-mgray c-bd1-ccc"></div>
              </div>
              <div class="c-flex-grow1 c-p c-pz10">
                <div class="c-fs26 c-fw600" :class="item.status == -1 ? 'c-fc-gray' : 'c-fc-xblack'">{{item.ticketName}}</div>
                <div class="c-mt16">参加人：{{item.name}}</div>
                <div class="c-mt16">联系电话：{{item.mobile}}</div>
                <template v-if="item.fieldVal && item.fieldVal.length && item.isShowAll">
                  <div v-for="(cItem,cIndex) in item.fieldVal" :key="cIndex" class="c-mt16">{{cItem.name}}：{{cItem.value}}</div>
                </template>
                <div class="c-flex-row c-aligni-center c-justify-sb c-mt16">
                  <div v-if="item.status != -1 && item.status != 0" class="">票号：{{item.ticketNo}}</div>
                  <div v-if="item.receiveUserId != 0 && item.receiveUserId != userId && from !='reservation'" class="c-ww106 c-hh36 c-flex-row c-flex-center theme-bg c-fc-white c-br20 c-fs20" @click.stop="showReciver(index)">领取详情</div>
                </div>
                <div v-if="item.fieldVal && item.fieldVal.length" @click.stop="clickChangeIsShow(index)" class="c-flex-row c-flex-center c-fs20 c-fc-gray c-mt16">
                  <span>{{item.isShowAll ? '收起':'展开全部'}}</span>
                  <i :class="item.isShowAll ? 'icon-shangfangxiangjian':'icon-xiafangxiang'" class="iconfont c-pl6 c-fs16 c-fc-gray"></i>
                </div>
              </div>
            </div>
            <div v-if="isShowGift(item)" class="c-pv18 c-ph24">
              <div @click.stop="openGifts(item)" :class="showShare ? 'c-pl48 c-boxSizing-b' : ''" class="c-w100 c-boxSizing-b c-fs22 c-flex-row c-fc-xblack c-aligni-center">
                <div class="c-mr20 c-fc-xblack c-fw-b c-fs22">赠品</div>
                <div class="c-flex-grow1">
                  <div class="c-fs22 c-flex-row c-aligni-center c-justify-sb">
                    <div class="c-br4 c-textAlign-c c-mr20 c-ph4 c-pv2 theme-bg-10 theme-fc c-fs16">礼包</div>
                    <div class="c-text-ellipsis1 c-fc-xblack">内含{{item.giftRelates && item.giftRelates.length}}个商品</div>
                    <div class="c-flex-grow1 c-flex-row c-aligni-center c-justify-end">
                      <div class="c-flex-row c-aligni-center theme-fc">
                        <span v-if="item.giftRelates[0] && item.giftRelates[0].userId == userId" class="c-fs22">{{item.giftRelatesStatus ? '查看' : '领取礼包'}}</span>
                        <span class="iconfont c-fs22">&#xe635;</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 约课当前签到不一样了，和上面的列表不同 -->
        <div class="c-w100 c-ph24" v-if="from == 'reservation'">
          <div class="c-w100 c-bg-white c-br12 c-pt24 c-pb22 c-ph24" @click="clickSelectList(index)" :class="index == ticketList.length - 1 ?'':'c-mb20'" v-for="(item, index) in ticketList" :key="index">
            <div class="c-w100 c-flex-row c-pb28 c-bd-b1">
              <div class="c-ww180 c-hh120 c-br10">
                <img class="c-ww180 c-hh120 c-br10" :src="$addXossFilter(item.poster || require('@/assets/defult270.png'))" alt="">
              </div>
              <div class="c-flex-column c-justify-sb c-flex-grow1 c-w0 c-ml14">
                <p class="c-w100 c-fs24 c-fc-xblack c-fw500 c-text-ellipsis1">{{item.themeName}}</p>
                <p class="c-w100 c-fs20 c-fc-gray c-text-ellipsis1">预约场次：{{item.sessionName}}</p>
                <p class="c-w100 c-fs20 c-fc-gray c-text-ellipsis1">预约码：{{item.ticketNo}}</p>
              </div>
            </div>
            <div class="c-flex-row c-justify-sb c-aligni-center c-pt18">
              <p class="c-w100 c-fs20 c-fc-gray c-text-ellipsis2" v-if="item.reservationMode == 1">预约时间：{{item.enrollTime}}</p>
              <p class="c-w100 c-fs20 c-fc-gray c-text-ellipsis2" v-if="item.reservationMode == 2">预约时间：{{item.startAt.substr(0,16) + "至 "+ item.endAt.substr(0,16)}}</p>
              <span class="iconfont c-fs32 theme-fc" v-if="item.isChecked == 1">&#xe82e;</span>
              <span class="iconfont c-fs32 c-fc-sgray" v-if="item.isChecked == -1">&#xe6f7;</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 分享 -->
      <div v-if="from == 'share' && enableShare" class="c-pf c-pz11 c-p-b0 c-w100 c-maxw640 c-bg-white">
        <div v-if="activityInfo.isCollectForm == 1 && !(ticketList.length == 1 && ticketList[0].receiveUserId == userId)" class="c-w100 c-hh60 c-flex-row c-aligni-center c-fs22 c-fc-xmlred c-bg-xmlred-10 c-ph24 c-boxSizing-b">
          <span class="iconfont c-mr10">&#xe963;</span>
          <span>建议单张分享，以免领取者与表单上的信息不一致！</span>
        </div>
        <div class="c-w100 c-ph24 c-maxw640 c-bg-white c-hh88 c-flex-row c-aligni-center c-justify-sb c-fs24" :class="activityInfo.isCollectForm == 1 && !(ticketList.length == 1 && ticketList[0].receiveUserId == userId) ? '' : 'c-box-shadowEdu'">
          <span v-if="showShare" @click="clickSelectAll" class="c-flex-shrink0 c-mr26">
            <span class="iconfont c-fs28" :class="selectAll ? 'theme-fc' : 'c-fc-sgray'">{{selectAll ? '&#xe796;' : '&#xe6f7;'}}</span>
            <span class="c-ml10">全选</span>
          </span>
          <div class="c-flex-grow1 c-flex-row c-aligni-center c-justify-end">
            <div v-if="showShare" class="c-hh64 c-flex-row c-flex-center c-br-tl40 c-br-bl40 theme-bg-10 theme-fc c-ww240" @click="clickCancel">取消</div>
            <div class="c-hh64 c-flex-row c-flex-center c-fc-white theme-bg" :class="showShare ? 'c-br-tr40 c-br-br40 c-ww240' : 'c-br40 c-w100'" @click="clickShare">赠送票券</div>
          </div>
        </div>
      </div>
      <!-- 签到 -->
      <div v-else-if="((from == 'signin' && signStatus == 1) || from == 'reservation') && ticketList.length > 0" class="c-ph24 c-pf c-pz11 c-p-b0 c-w100 c-maxw640 c-bd-t1 c-bg-white c-hh88 c-flex-row c-aligni-center c-justify-sb c-fs26">
        <div class="c-fs24 c-fc-xblack c-hh64 c-flex-row c-flex-center c-mr36" @click="clickSelectAll">
          <i class="iconfont c-fs28 c-mr8" :class="selectAll ?'theme-fc':'c-fc-sgray'">{{selectAll ? '&#xe82e;':'&#xe6f7;'}}</i>
          <span>全选</span>
        </div>
        <div class="c-fc-white c-lh c-flex-row c-flex-center c-br36 theme-bg c-hh64 c-flex-grow1 c-w0" @click="clickSign">签到&nbsp; <span v-show="choosedLength > 0">({{choosedLength}})</span></div>
      </div>
    </div>

    <div class="c-fc-sgray c-fs20 c-textAlign-c c-pv20" v-if="isLoading || (dataStatus == 'NO_MORE_DATA' && (signStatus == 1 || asId ==0 ))">{{isLoading ? '加载中...' : '我是有底线的'}}</div>
    <loading-status-tem :noDataText="signMsg == '还没开始签到！' ? '还没开始签到!' : signMsg == '签到已结束！' ? '签到已结束!' : '暂无相关票券'" :noData="signStatus == -1 || !isLoading && dataStatus == 'NO_DATA'" :noneImage="signMsg == '还没开始签到！' ? notStarte : signMsg == '签到已结束！' ? end : noData" :isActivity="true"></loading-status-tem>
    <div class="c-ww120 c-hh50 c-lh50 c-br10 c-fc-white c-fs24 c-mt20 theme-bg c-mlr-auto c-textAlign-c" v-if="signStatus == -1 || (signStatus == 1 && ticketList.length == 0)" @click="goActivityDetail">查看活动</div>
    <!-- 领取详情 -->
    <cj-popup v-model="showGetDetail" round>
      <div class="c-ww500 c-p c-flex-column c-flex-center c-pv40 c-ph80">
        <div class="c-pa c-p-t0 c-p-l0 c-br-tl16 c-br-tr16 c-pz-1 c-w100 c-hh200 theme-bg-gradient18020 c-opacity40"></div>
        <p class="c-fs32 c-fw600">票券领取详情</p>
        <img class="c-brp50 c-ww100 c-hh100 c-mt40" :src="$addXossFilter(reciveInfo.reHeadimgurl, require('@/assets/defult_head.png'))" alt="">
        <p class="c-fs30 c-mt20">{{reciveInfo.receiveName}}</p>
        <p class="c-fs24 c-fc-gray c-mt20">已成功领取您赠送的票券</p>
        <div @click="showGetDetail = false" class="c-mt40 c-ww340 c-hh76 theme-bg c-fc-white c-fs30 c-fw600 c-br40 c-flex-row c-flex-center">我知道了</div>
        <p class="c-fs24 c-fc-gray c-mt20">领取时间：{{reciveInfoTime}}</p>
      </div>
    </cj-popup>

    <!-- 生成分享票券图片 -->
    <div v-show="showShareModal" @click.stop="showShareModal = false" class="c-pf c-pz100 c-p-t0 c-h c-w100 c-maxw640 c-translucent-balck60 c-ph30 c-pt120 c-br8">
      <img @click.stop="" src="https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/i/wap/activity/https://ck-bkt-knowledge-payment.oss-cn-hangzhou.aliyuncs.com/admin/material/9_material_admin/image/assets/i/wap/activity/present_ticket_bg.png.png" class="c-w100" id="cuetImg" />
      <div class="c-mt20 c-fs24 c-fc-white c-flex-row c-flex-center">长按保存图片分享给好友</div>
    </div>
    <!-- 赠送礼包 -->
    <gift-modal :tipText="giftTipText" :isShowBtn="isShowGiftBtn" :fromProdType="7" :hasBuy="true" :showGiftModal="showGifts" :fromCourseId="activityId" :prodList="giftRelates" @closeGift="closeGift" @receiveGiftSuccess="receiveGiftSuccess"></gift-modal>
  </div>
</template>
<script>
import { utilJs } from "@/utils/common.js";
import loadingStatusTem from "@/components/templates/common/loadingStatusTem.vue";
import giftModal from '@/components/templates/giftModal';
import CoverImg from '@/components/templates/common/coverImg.vue';
import { Json2canvas } from '@/utils/json2image.js';
import { getTicketJson } from '@/utils/canvasJson/activityTicketJson.js';

const HANDLE_TAGS = 536870912;// 原本24是赠送，现在改为这个值
const THEME_RGB_MAP = global.THEME_RGB_MAP;
let isClick = false;
let pageIndex = 1;
export default {
  name: "MyTicket",
  components: {
    loadingStatusTem,
    giftModal,
    CoverImg
  },
  data() {
    return {
      themeColor: localStorage.getItem("colorName") || 'mb5_default',
      userId: localStorage.getItem("userId"),
      activityInfo: "",
      ticketList: [],
      pageLimit: 10,
      isLoading: false,
      enrollStartAt: "",
      enrollEndAt: "",
      statusMap: {
        "-2": "拼团中",
        "-1": "已作废",
        "0": "待审核",
        "1": "待签到",
        "2": "待付款",
        // "3": "已结束",
        "4": "已签到",
        "5": "使用中",
      },
      total: 0,
      showGetDetail: false,
      showShare: false, //显示分享
      selectAll: false, //是否全选
      choosedLength: 0, //选择的票券数量
      currentIndex: 0, //当前点击的索引
      reciveInfo: "", //领取人信息
      reciveInfoTime: "", //领取人信息
      showShareModal: false,
      from: "share",
      enableShare: false,
      dataStatus: 'NO_MORE_DATA',
      rsId: "",
      asId: "",
      signName: "",
      isSignRepeatedly: "", //是否多次签到
      signStatus: "",
      signMsg: "",
      page: 1,
      pageIndex: 1,
      notStarte: require('@/assets/i/wap/activity/notStarte.png'),
      noData: "https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/i/wap/activity/noData.png",
      end: "https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/i/wap/activity/end.png",
      giftRelates: {}, // 礼包列表详情
      showGifts: false, // 是否展示礼包弹窗
      isShowGiftBtn: true, // 是否展示领取/查看按钮
    };
  },
  created() {
    utilJs.appShare(this);
  },
  watch: {
    ticketList: {
      handler(newList, oldList) {
        //获取选中的票券
        let selectArr = newList.filter(item => {
          return item.isChecked == 1;
        });
        this.choosedLength = selectArr.length;
      },
      immediate: true,
      deep: true
    }
  },
  computed: {
    giftTipText() {
      // 礼包领取设置: giftDeliveryMethod 1报名成功后即可领取  2首次签到后可领取
      return `<p>赠品需要等${this.activityInfo && this.activityInfo.giftDeliveryMethod == 2 ? '首次签到后可领取' : '报名审核通过'}后，回到当前页面手动领取</p><p class="c-fc-red">注：礼包领取后，该票券就不能继续赠送给他人了</p>`;
    }
  },
  methods: {
    getStatusClass(item = {}) {
      if (item.status == 1 && (item.receiveUserId == 0 || item.receiveUserId == this.userId)) { // 待签到
        return 'c-bg-xmlred'
      } else if (item.status == 4) { // 已签到
        return 'c-bg-03BA50'
      } else if (item.status == -1) { // 已作废
        return 'c-bg-ccc'
      }
      return 'theme-bg'
    },
    receiveGiftSuccess() {
      this.getMyTicket();
    },
    closeGift() {
      this.showGifts = false;
    },
    // 是否领取过该票券里的礼包
    isReceiveGift(item = {}) {
      //  有礼包 && 礼包中有商品被领取了
      if (this.from != 'signin' && this.from != 'reservation' && item.giftRelates && item.giftRelates.length && item.giftRelates.findIndex(gItem => gItem.status == 1) > -1) {
        return true
      }
      return false
    },
    isShowGift(item) {
      // 有礼包 && (待审核 || 待签到 || 已签到 || 使用中)
      return item.giftRelates && item.giftRelates.length && (item.status == 0 || item.status == 1 || item.status == 4 || item.status == 5)
    },
    openGifts(item) {
      this.showGifts = true
      this.giftRelates = item.giftRelates
      // 判断礼包所属权，不是自己的礼包，弹窗不展示领取/查看按钮
      // this.giftRelates[0].userId礼包所属人id，礼包只会有一个归属人，所以只需要判断礼包其中一个商品的userId
      this.isShowGiftBtn = this.giftRelates[0].userId == this.userId
    },
    getEnrollToSign() {
      if (this.dataStatus == 'LOADING') {
        return
      }
      this.dataStatus = 'LOADING';
      utilJs.getMethod(global.apiurl + `reservations/getEnrollToSign?page=${this.page}&index=${this.pageIndex}&limit=${this.pageLimit}`, res => {
        if (this.pageIndex == 1) {
          this.ticketList = res.data;
        } else {
          this.ticketList = [...this.ticketList, ...res.data];
        }
        let newTicketList = this.ticketList.map(v => {
          return {...v, isChecked: -1, status: 1}
        })
        this.ticketList = newTicketList;
        if (res.to * 1 == this.ticketList.length) {
          this.dataStatus = res.to * 1 == 0 ? "NO_DATA" : "NO_MORE_DATA";
        } else {
          this.dataStatus = 'HAS_MORE_DATA';
          this.pageIndex += this.pageLimit;
          this.page++;
        }
      }, failRes => {
        this.dataStatus = "DATA_ERROR"
      })
    },
    // 点击取消
    clickCancel() {
      let curTickList = [...this.ticketList]
      for (let item of curTickList) {
        this.$set(item, "isChecked", -1);
      }
      this.ticketList = [...curTickList]
      this.selectAll = false
      this.showShare = false;
    },
    // 点击签到
    clickSign() {
      let choosedArr = [];
      for (let item of this.ticketList) {
        if (item.isChecked == 1) {
          choosedArr.push(item.id);
        }
      }
      this.choosedLength = choosedArr.length;
      if (this.choosedLength == 0) {
        this.$showCjToast({
          text: "请选择要签到的票券",
          type: "warn",
        });
      } else {
        this.signUp(choosedArr);
      }
    },
    //活动签到
    signUp(aeIdArr) {
      if (isClick) {
        return;
      }
      isClick = true;
      let $this = this;
      if (this.from == 'reservation') {
        let data = {
          rtId: this.activityId,
          rsId: this.rsId,
          reIdArr: aeIdArr
        }
        utilJs.postMethod(`${global.apiurl}reservations/signUp`, data,
          function (res) {
            isClick = false;
            if (res.retError == 1) {
              let ticketNo = [];
              for (let item of res.data) {
                ticketNo.push(item.ticketNo)
              }
              $this.$routerGo($this, "replace", { path: `/activity/signResult`, query: { num: $this.choosedLength, activityId: $this.activityId, ticketNo: JSON.stringify(ticketNo), channel: 'activity', comeFrom: 'reservation', rsId: $this.rsId } })
            } else {
              $this.$showCjToast({
                text: res.msg,
                type: "warn",
                isShowMask: "true"
              });
            }
          }
        );
      } else {
        let data = {
          activityId: this.activityId,
          aeIdArr: JSON.stringify(aeIdArr),
          asId: this.asId,
        }
        utilJs.postMethod(`${global.apiurl}activities/signUp`, data,
          function (res) {
            isClick = false;
            // -1：签到失败，1：签到成功
            if (res.retError == -1) {
              $this.$showCjToast({
                text: res.msg,
                type: "warn",
                isShowMask: "true"
              });
            } else if (res.retError == 1) {
              let ticketNo = [];
              for (let item of res.data) {
                ticketNo.push(item.ticketNo)
              }
              $this.$routerGo($this, "replace", { path: `/activity/signResult`, query: { num: $this.choosedLength, activityId: $this.activityId, ticketNo: JSON.stringify(ticketNo), channel: 'activity' } })
            }
          }
        );
      }
    },
    // 点击领取详情
    showReciver(index) {
      this.reciveInfo = this.ticketList[index];
      this.reciveInfoTime = this.ticketList[index].enrollTime.substr(0, 10);
      this.showGetDetail = true;
    },
    clickSelectList(index) {
      if (this.ticketList[index].status != 1 || (this.ticketList[index].receiveUserId != 0 && this.from != 'signin' && this.from != 'reservation')) {
        return
      }
      if (this.showShare && this.ticketList[index].enableShare != 1) {
         this.$showCjToast({
            text: this.isReceiveGift(this.ticketList[index]) ? '您已领取当前票的礼包，不可转增给他人' : '当前票不可赠送',
            type: "warn",
          });
        return;
      }
      let curTickList = [...this.ticketList];
      let isChecked = this.ticketList[index].isChecked;
      if (isChecked == -1) {
        this.$set(curTickList[index], "isChecked", 1);
        let selectArr = curTickList.filter(item => {
          return item.isChecked == 1;
        });
        // 筛选出可选的列表，在进行长度判断是否全选
        const canSelectList = this.from == 'share' ? curTickList.filter(i => i.status == 1 && i.receiveUserId == 0 && i.enableShare == 1) : curTickList
        if (selectArr.length == canSelectList.length) {
          this.selectAll = true;
        }
      } else {
        this.selectAll = false;
        this.$set(curTickList[index], "isChecked", -1);
      }
      this.ticketList = [...curTickList];
    },
    //点击全选
    clickSelectAll() {
      this.selectAll = !this.selectAll;
      let curTickList = [...this.ticketList];
      if (this.selectAll) {
        for (let key of curTickList) {
          if (key.status == 1 && ((key.receiveUserId == 0 && key.enableShare == 1 && this.from != "signin") || (this.from == "signin" || this.from == "reservation"))) {
            key.isChecked = 1;
          }
        }
      } else {
        for (let key of curTickList) {
          key.isChecked = -1;
        }
      }
      this.ticketList = [...curTickList];
    },
    // 点击分享票券
    clickShare() {
      if (this.showShare) {
        let choosedArr = [];
        for (let item of this.ticketList) {
          if (item.isChecked == 1) {
            choosedArr.push(item.id)
          }
        }
        this.choosedLength = choosedArr.length;
        if (this.choosedLength == 0) {
          this.$showCjToast({
            text: "请选择分享票券",
            type: "warn",
            time: 1500,
            isShowMask: "true",
          });
          return
        }
        this.getShareQrcode(choosedArr);
      } else {
        this.showShare = true;
      }
    },
    //获取分享二维码
    getShareQrcode(aeIdArr) {
      if (isClick) {
        return;
      }
      isClick = true;
      let data = {
        activityId: this.activityId,
        aeIdArr: JSON.stringify(aeIdArr)
      }
      utilJs.postMethod(`${global.apiurl}activities/getShareQrcode`, data,
         (res) => {
          isClick = false;
          let activityInfo = this.activityInfo;
          let price = Number(this.ticketList[0].price);
          let sharePrice = "";
          if (price == 0) {
            sharePrice = "免费"
          } else {
            sharePrice = price.toFixed(2)
          }
          this._shareInfo = {
            bgImgUrl: this.$addXossFilter("https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/i/wap/activity/present_ticket_bg.png"),
            cover: activityInfo.poster || require('@/assets/activity_defult.png'),
            name: activityInfo.name,
            place: activityInfo.place,
            time: `活动时间：${this.enrollStartAt} 至 ${this.enrollEndAt}`,
            ticketName: this.ticketList[0].ticketName,
            price: sharePrice,
            num: this.choosedLength,
            qrcodeImg: res,
            fontColor: `rgb(${THEME_RGB_MAP[this.themeColor]})`
          }
          this.getTicketImg();
        }
      );
    },
    initJson2image() {
      this._json2image = new Json2canvas({
        width: 870,
        height: 1245
      });
    },
    destroyJson2image() {
      if (this._json2image) {
        this._json2image.destroy();
      }
    },
    async getTicketImg() {
      if (!this._json2image) {
        return;
      }
      this.$loading.show({
        text: '票券生成中'
      });

      let res = '';
      console.time('json2imageTime');
      console.time('loadImgTime');
      try {
        await this._json2image.init();
        const data = getTicketJson(this._shareInfo, this._json2image);
        console.log('data', data);
        await this._json2image.initJson(data);
        console.timeEnd('loadImgTime');
        console.time('drawTime');
        await this._json2image.startDraw();
        console.timeEnd('drawTime');
        console.time('toDataUrlTime');
        res = await this._json2image.toDataUrl();
        console.timeEnd('toDataUrlTime');
      } catch (error) {
        console.log('err', error);
        this.$loading.hide();
      }
      if (!res) {
        this.$loading.hide();
        return;
      }
      this.isShow = true;
      let ig = document.getElementById('cuetImg');
      ig.setAttribute('src', res);
      this.$loading.hide();
      console.timeEnd('json2imageTime');
      this.showShareModal = true;
    },
    getActicityInfo() {
      let $this = this;
      let url = this.from == "reservation" ? `reservations/getSessionInfo?rtId=${this.activityId}&rsId=${this.rsId}` : `activities/getShareActivtiyInfo?activityId=${this.activityId}`
      utilJs.getMethod(`${global.apiurl}${url}`,
        function (res) {
          $this.userId = localStorage.getItem("userId");
          $this.getMyTicket();
          $this.activityInfo = res;
          if ($this.from != "reservation") {
            $this.enrollStartAt = res.enrollStartAt.substr(5, 11);
            $this.enrollEndAt = res.enrollEndAt.substr(5, 11);
          }
        }
      );
    },
    getMyTicket() {
      let $this = this;
      if (!this.isLoading) {
        this.isLoading = true;
        // identCode报名标识（type=1 时传） type1：我的票券页面
        let url = this.from == "reservation" ? `reservations/getTicketByCode?rtId=${this.activityId}&rsId=${this.rsId}` : `activities/getTicketByCode?activityId=${this.activityId}&identCode=${this.$route.query.identCode || ""}&type=${this.from == 'signin' ? 2 : 1}&asId=${this.asId}`
        utilJs.getMethod(`${global.apiurl}${url}&limit=${this.pageLimit}&page=${pageIndex}`,
          (res) => {
            $this.isLoading = false;
            $this.total = res.enrollList.total;
            if ($this.asId != 0) {
              $this.signName = res.info.signName;
              $this.isSignRepeatedly = res.info.isSignRepeatedly;
              $this.signMsg = res.info.msg;
              $this.signStatus = res.info.status;
            }
            for (let item of res.enrollList.data) {
              item.isChecked = -1;
              item.isShowAll = false;
              item.fieldVal = $this.resetFormData(item.fieldVal);
              // 是否包含未领取的商品
              const index = item.giftRelates.findIndex(gItem => gItem.userId == $this.userId && gItem.status != 1)
              item.giftRelatesStatus = index < 0 // 不包含则全部已领取，整体状态giftRelatesStatus为已领取
            }
            if (pageIndex == 1) {
              $this.ticketList = res.enrollList.data;
            } else {
              $this.ticketList = [...$this.ticketList, ...res.enrollList.data];
            }
            if (res.enrollList.next_page_url) {
              $this.dataStatus = 'HAS_MORE_DATA';
              pageIndex++
            } else {
              $this.dataStatus = res.enrollList.data == 0 ? 'NO_DATA' : 'NO_MORE_DATA';
            }
            if ($this.from != "reservation") {
              for (let item of $this.ticketList) {
                // 权限来源=后台添加，不允许赠送
                if (item.enableShare == 1 && item.tags != HANDLE_TAGS) {
                  $this.enableShare = true;
                  return
                } else {
                  $this.enableShare = false;
                }
              }
            }
          }
        );
      }
    },
    resetFormData(data) {
      if (!data) {
        return [];
      }
      for (let item of data) {
        let options = item.options;
        let value = item.value
        //单选
        if (item.dataType == 5) {
          item.value = options[value];
        }
        //多选
        if (item.dataType == 6) {
          let arr = [];
          for (let i of value) {
            arr.push(options[i]);
          }
          item.value = arr.join(',');
        }
        if (item.dataType == 7 && value && value.name) {
          item.value = `${value.name.join(' ')} ${value.addressDetail}`;
        }
      }
      return data;
    },
    clickChangeIsShow(index) {
      this.ticketList[index].isShowAll = !this.ticketList[index].isShowAll;
    },
    toTicketNum(status, receiveUserId) {
      //非已作废&&非未审核
      if (((status == 1 || status == 4) && (receiveUserId == 0 || receiveUserId == this.userId)) && !this.showShare && this.from != 'signin') {
        // 点击查看票券
        this.$routerGo(this, "push", {
          path: `/activity/ticketNum`,
          query: { activityId: this.activityId, identCode: this.$route.query.identCode, from: 'activity' }
        });
      }
    },
    goActivityDetail() {
      if (this.from == 'reservation') {
        this.$routerGo(this, "push", {
          path: "/activity/activityDetail",
          query: {
            from: "reservation",
            ActivityNo: this.activityId,
          }
        })
      } else {
        this.$routerGo(this, "push", {
          path: "/activity/activityDetail",
          query: {
            ActivityNo: this.activityId,
          }
        })
      }
    },
    windowScrollFunction: function () {
      let that = this;
      utilJs.handleLoading(function () {
        if (that.dataStatus == 'HAS_MORE_DATA' && that.ticketList.length > 0) {
          if (that.from == 'reservation') {
            that.getEnrollToSign();
          } else {
            that.getMyTicket();
          }
        }
      });
    },
    //分享
    wechatShare: function () {
      utilJs.wechatConfig("", "", "", "", function () { });
    },
    //手机端分享
    appShare: function () {
      utilJs.appShareTrue("", "", "", "");
    },
  },
  activated() {
    setDocumentTitle("我的票券");// eslint-disable-line
    isClick = false;
    pageIndex = 1;
    this.dataStatus = 'NO_MORE_DATA';
    this.activityId = this.$route.query.activityId || "";
    this.from = this.$route.query.from || "share";
    this.rsId = this.$route.query.rsId || "";
    this.asId = this.$route.query.asId || "";
    this.activityInfo = "";
    this.shareInfo = {};
    this.ticketList = [];
    this.enrollStartAt = "";
    this.enrollEndAt = "";
    this.reciveInfo = "";
    this.reciveInfoTime = "";
    this.signName = "";
    this.isSignRepeatedly = ""; //是否多次签到
    this.signStatus = "";
    this.signMsg = "";
    this.pageLimit = 10;
    this.isLoading = false;
    this.showShare = false;
    this.showGetDetail = false;
    this.showShareModal = false;
    this.total = 0;
    this.choosedLength = 0;
    this.currentIndex = 0;
    this.selectAll = false; //是否全选
    this.enableShare = false;
    this.page = 1;
    this.pageIndex = 1;
    this.giftRelates = {}; // 礼包列表详情
    this.showGifts = false; // 是否展示礼包弹窗
    this.isShowGiftBtn = true; // 是否展示领取/查看按钮
    this.initJson2image();
    if (this.from != 'reservation') {
      this.getActicityInfo();
    } else {
      this.getEnrollToSign();
    }
    window.addEventListener('scroll', this.windowScrollFunction);
    this.wechatShare();
  },
  deactivated() {
    this.destroyJson2image();
    isClick = false;
    this.dataStatus = 'NO_MORE_DATA';
    window.removeEventListener('scroll', this.windowScrollFunction);
  }
};
</script>
<style scoped>
</style>


